#!/bin/bash

set -e

echo -e "\e[32m[1/7] 正在安装依赖...\e[0m"
yum -y install gcc openldap-devel pam-devel openssl-devel wget curl

echo -e "\e[32m[2/7] 正在下载 SS5 源码...\e[0m"
#原下载  wget -O ss5.tar.gz http://jaist.dl.sourceforge.net/project/ss5/ss5/3.8.9-8/ss5-3.8.9-8.tar.gz
wget -O ss5.tar.gz https://gitee.com/git220/auto-jb/releases/download/v3.8.9-8/ss5-3.8.9-8.tar.gz

echo -e "\e[32m[3/7] 正在解压编译安装...\e[0m"
tar xvf ss5.tar.gz
cd ss5-3.8.9
./configure && make && make install

echo -e "\e[32m[4/7] 正在配置用户名和端口...\e[0m"
echo '123 123' > /etc/opt/ss5/ss5.passwd
echo 'SS5_OPTS=" -u root -b 0.0.0.0:16585"' > /etc/sysconfig/ss5

echo -e "\e[32m[5/7] 正在修改认证配置...\e[0m"
cat > /etc/opt/ss5/ss5.conf <<EOF
auth    0.0.0.0/0       -       u
permit  u               0.0.0.0/0       -       0.0.0.0/0       -       -       -       -       -
EOF

echo -e "\e[32m[6/7] 设置开机启动并启动服务...\e[0m"
cat > /etc/systemd/system/ss5.service <<EOF
[Unit]
Description=SS5 Socks Proxy
After=network.target

[Service]
Type=forking
ExecStart=/usr/sbin/ss5 -u root -b 0.0.0.0:16585
PIDFile=/var/run/ss5/ss5.pid
ExecStartPre=/bin/mkdir -p /var/run/ss5
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable ss5
systemctl restart ss5
#chmod +x /etc/init.d/ss5
#chkconfig --add ss5
#chkconfig --level 345 ss5 on
#service ss5 restart

echo -e "\e[32m[7/7] 测试代理功能...\e[0m"
IP=$(curl --socks5 127.0.0.1:16585 -U 123:123 -s http://ifconfig.me || echo "失败")

if [[ "$IP" == "失败" || -z "$IP" ]]; then
    echo -e "\e[31m❌ 代理测试失败，请检查ss5服务或端口是否正常。\e[0m"
else
    echo -e "\e[32m✅ 代理工作正常，当前出口IP为：$IP\e[0m"
fi

echo -e "\n\e[1;36mSS5   安 装 完 成 ！！！\e[0m"
echo -e "\e[33m默认用户名: 123 密码: 123\e[0m"
echo -e "\e[33m监听端口  : 16585\e[0m"
echo -e "\e[33m重置密码  : sudo nano /etc/opt/ss5/ss5.passwd\e[0m"
echo -e "\e[33m更改端口  : sudo nano /etc/sysconfig/ss5 \e[0m"
echo -e "\e[33m手动测试IP: curl --socks5 127.0.0.1:16585 -U 123:123 http://ifconfig.me \e[0m"